package com.mzy.linear_struct;

/**
 * @Author: codermzy
 * @Date: 2024/05/10/下午5:28
 * @Description:
 */
public class SortedLinkedList {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

    }

    public ListNode sortList(ListNode head) {
        ListNode newHead = mergeSort(head);
        return newHead;
    }

    public ListNode mergeSort(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        ListNode right = null;
        //         f
        // 1 2 3 4
        //     s
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //
        right = slow.next;
        slow.next = null;
        // slow是中点
        // 从中点切断
        divideListNode(head, slow);
        return null;
    }

    private void divideListNode(ListNode head, ListNode mid) {
        if (head.next == null) return;

        ListNode slow = head;
        ListNode fast = head;

        while (fast != mid && fast.next != mid) {
            slow = slow.next;
            fast = fast.next.next;
        }
        slow.next = null;
        System.out.println(slow.val);
        divideListNode(head, slow);
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4))));
        new SortedLinkedList().mergeSort(head);
    }
}